class SessionsController < ApplicationController
  SESSION_EXPIRE_TIME = 2.hours

  skip_before_action :check_login
  layout 'login'

  def change_locale
    if I18n.locale_available?(params[:locale])
      session[:locale] = params[:locale]
      show_js_notice "#{ts :change_language, :success}"
    else
      error_notice("#{ts :change_language, :fail}")
    end
  end

  def login
    if current_user.present?
      flash[:notice] = '请先退出登录！'
      return redirect_to '/'
    end
    @user = User.new
  end

  def do_login
    if user = User.valid_user(params[:user])
      flash[:notice] = '登陆成功！'
      session[:current_user_id] = user.id
      session[:expire_at] = Time.now + SESSION_EXPIRE_TIME
      redirect_to session[:login_referer]||root_path
    else
      error_notice '登陆失败，请检查用户名密码！'
    end
  end

  def logout
    clear_session
    flash[:notice] = '成功退出！'
    redirect_to login_path
  end


  def register
    @html_title = '账号注册'
  end

  def do_register
    return error_notice '暂未开放！'
    # u = User.new(name: params[:name], username: params[:username], password: params[:password])
    # if u.save
    #   flash[:notice] = '注册成功！'
    #   redirect_to root_path
    # else
    #   error_notice(u)
    # end
  end

  def forgot
    @html_title = '忘记密码'
  end

  def do_forgot
    return error_notice '暂未开放！'
    # user = User.active.where(mobile: params[:mobile])
    # return error_notice('该手机号尚未注册或已被禁用！') if user.blank?
    # # update_all 是要直接更新数据库的，所以要加密一遍
    # user.update_all(password: Digest::MD5.hexdigest(params[:password]))
    # flash[:notice] = '密码重置成功！'
    # redirect_to root_path
  end
end
